package org.gjy.m8.concurrent.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.StampedLock;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-13 10:36:45
 */
public class AbcPrint {

    private static final Lock lock = new ReentrantLock();
    private static final Condition a = lock.newCondition();
    private static final Condition b = lock.newCondition();
    private static final Condition c = lock.newCondition();
    private static final AtomicInteger single = new AtomicInteger(0);

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        pool.execute(() -> {
            lock.lock();
            try {
                if (single.get() != 0) {
                    a.await();
                }
                System.out.println("A");
                TimeUnit.SECONDS.sleep(2);
                single.compareAndSet(0, 1);
                b.signal();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        });
        pool.execute(() -> {
            lock.lock();
            try {
                if (single.get() != 1) {
                    b.await();
                }
                System.out.println("B");
                TimeUnit.SECONDS.sleep(2);
                single.compareAndSet(1, 2);
                c.signal();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        });

        pool.execute(() -> {
            lock.lock();
            try {
                if (single.get() != 2) {
                    c.await();
                }
                System.out.println("C");
                TimeUnit.SECONDS.sleep(2);
                single.compareAndSet(2, 0);
                a.signal();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        });

        pool.shutdown();
    }
}
